<template>
  <div class="dashboard">
    <SearchForm
      ref="searchFormcen"
      :data="propForm"
      :dataHandler="propHandler"
    />
    <PublicTable
      :isLoading="isLoading"
      :tableInfo="tableInfo"
      :pagination="true"
      :pageData="pageData"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <Dialog ref="dialog" :title="title" :buttons="buttons" @closeDialog="closeDialog" width="540px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" label-position="rigth">
        <el-form-item label="会议主题:" prop="meetingSubject">
          <el-input placeholder="请输入会议主题" v-model="form.meetingSubject" size="mini" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="会议时间:" prop="date">
          <el-date-picker v-model="form.date" type="datetimerange" range-separator="至" :picker-options="pickerOptions" @change="changeDate"
          start-placeholder="开始时间" end-placeholder="结束时间" size="mini" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会议室:" prop="roomId">
          <el-select v-model="form.roomId" placeholder="请选择会议室" filterable size="mini" style="width: 400px">
            <el-option v-for="item in roomOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通知时间:" prop="noticeTime">
          <el-input placeholder="请输入分钟" v-model="form.noticeTime" size="mini" type="number" style="width: 400px;margin-top: 6px">
            <template slot="append">提前{{form.noticeTime ? form.noticeTime : 'xx'}}分钟通知参会人员</template>
          </el-input>
        </el-form-item>
        <el-form-item label="参会人员:" prop="user">
          <el-select v-model="form.user" multiple placeholder="请选择" filterable size="mini" style="width: 400px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import { listPage, getCompanyUser, getFreeMeetingRoom, add, modify, modifyMeetingStatus } from "../../api/conferenceMng";
export default {
  data() {
    return {
      propForm: [
        {
          name: "会议主题",
          type: "input",
          key: "subject",
          placeholder: "请输入会议主题",
          required: false,
          width: "100px",
        },
        {
					name: "会议时间",
					type: "timeSlot",
					key: "date",
					zhan: true,
					placeholder: ["开始时间", "结束时间"],
					required: false,
					defaultTime: ["00:00:00", "23:59:59"],
					valueformat: "yyyy-MM-dd HH:mm:ss",
				},
        {
          type: "button",
          button: [
            {
              name: "搜索",
              color: "primary",
              method: (c) => {
                this.searchData(c)
              },
            },
            {
              name: "清空",
              color: "info",
              method: (c) => {
                this.searchData(c, true)
              },
              clean: true,
            },
          ],
        },
      ],
      propHandler: [
        {
				  info: "新增会议",
				  icon: "el-icon-plus",
				  color: "#3370ff",
				  method: (c) => {
            this.roomOptions = []
            this.title = '新增会议'
				    this.$refs.dialog.show()
				  },
				}, 
      ],
      tableInfo: {
        selectable: true,
        tableConfig: [
          {
            label: "ID",
            prop: "id",
          },
          {
            label: "会议主题",
            prop: "meetingSubject",
          },
          {
            label: "会议室",
            prop: "meetingRoomName",
          },
          {
            label: "会议状态",
            prop: "statusMessage",
            width: 80
          },
          {
            label: "参会人员",
            prop: "joinUserName",
          },
          {
            label: "开始时间",
            prop: "startTime",
          },
          {
            label: "结束时间",
            prop: "endTime",
          },
          {
            type: "buttons",
            label: "操作",
            width: "200px",
            align: "center",
            fixed: "right",
            list: [
              {
                type: "success",
                text: "修 改",
                show: (row) => {
                  return !row.status && row.showBtn
                },
                events: (row) => {
                  this.form = row
                  this.$set(this.form,'date',[row.startTime,row.endTime])
                  this.$set(this.form,'roomId', row.roomId)
                  this.$set(this.form,'user', row.joinUser.split(','))
                  this.title = '修改会议'
                  this.$refs.dialog.show()
                  this.getFreeMeetingRoom(this.form.date,row.id)
                  
                },
              },
              {
                type: "danger",
                text: "取消会议",
                show: (row) => {
                  return !row.status && row.showBtn
                },
                events: (row) => {
                  this.$confirm('确定取消该会议?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                
                    modifyMeetingStatus({
                      status: -1,
                      meetingId: row.id
                    }).then(res => {
                      if (res.code == 200) {
                        this.$message.success(res.message)
                        this.getList()
                      } else this.$message.error(res.message)
                    })
                  })
                },
              },
              {
                type: "danger",
                text: "结束会议",
                show: (row) => {
                  return row.status == 1 && row.showBtn
                },
                events: (row) => {
                  this.$confirm('确定结束该会议?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    modifyMeetingStatus({
                      status: 2,
                      meetingId: row.id
                    }).then(res => {
                      if (res.code == 200) {
                        this.$message.success(res.message)
                        this.getList()
                      } else this.$message.error(res.message)
                    })
                  })
                },
              }
            ],
          },
        ],
        tableData: [],
      },
      pageData: {
        pindex: 1,
        psize: 10,
        total: 0,
      },
      searchDatas: {
        subject: "",
        date: []
      },
	    isLoading: false,
      title: '新增会议',
      buttons: [
        {
          type: "primary",
          title: "确认",
          loading: false,
          method: () => {
            this.submit()
          },
        },
        {
          title: "取消",
          method: () => {
            this.closeDialog()
            this.$refs.dialog.show()
          },
        },
      ],
      form: {
        meetingSubject: "",
        date: "",
        roomId: '',
        noticeTime: "",
        user: []
      },
      rules: {
        meetingSubject: { required: true, message: "请输入会议室名", trigger: ['blur', 'change'] },
        date: { required: true, message: '请选择会议时间', trigger: ['blur', 'change'] },
        roomId: { required: true, message: '请选择会议室', trigger: ['blur', 'change'] },
        noticeTime: { required: false, message: '请输入会议通知时间', trigger: ['blur', 'change'] },
        user: { required: false, message: '请选择参会人员', trigger: ['blur', 'change'] }
      },
      options: [],
      roomOptions: [],
      pickerOptions: {
        // 禁用当前时间之前的日期
        disabledDate: (time) => {          
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
    };
  },
  mounted() {
    this.getList()
    this.getCompanyUser()
    if(Object.keys(this.$route.params).length) {
      this.roomOptions = []
      this.$set(this.form,'date',this.$route.params.date)
			this.$refs.dialog.show()
      this.getFreeMeetingRoom(this.$route.params.date)
    }
  },
  watch: {
    // 'form.date'(newVal) {
    //   if(newVal.length) this.getFreeMeetingRoom(newVal)
    // }
  },
  methods: {
    changeDate(val) {
      console.log(val);
      
      if(!val.length) return
      const currentTime = new Date();
      const startTime = new Date(val[0]);
      const endTime = new Date(val[1]);
      // 判断给定时间是否大于当前时间
      const result = startTime > currentTime;
      const result2 = endTime > startTime;      
      if(!result) return this.$message.error('开始时间需在当前时间后')
      if(!result2) return this.$message.error('结束时间需在开始时间后')
      const startTime2 = new Date(val[0]).getHours();
      const endTime2 = new Date(val[1]).getHours();
      if (startTime2 < 9 || endTime2 > 18) return this.$message.error('时间范围必须在 09:00 - 18:00 之间');
      this.getFreeMeetingRoom(val)
    },
    //搜索
    searchData(c, close) {
      this.searchDatas.subject = close ? "" : c.subject;
      this.searchDatas.startTime = close ? "" : c.date[0];
      this.searchDatas.endTime = close ? "" : c.date[1];
      console.log(c);
      
      this.pageData.pindex = 1;
      this.getList();
    },
    //列表
    getList(tag) {
      let params = {
        page: this.pageData.pindex,
        pageSize: this.pageData.psize,
        ...this.searchDatas,
      };
      this.isLoading = true;
      listPage(params).then((res) => {
        this.isLoading = false;        
        if (res.code == 200) {
          this.tableInfo.tableData = res.data.data;
          this.tableInfo.tableData.forEach(i => {
            i.statusVal = i.status == 0 ? '空闲中' : i.status == 1 ? '使用中' : '暂停使用'
          })
          this.pageData.total = res.data.total || 0;
        } else this.$message.error(res.message);
      });
    },
    //控制翻页
    handleCurrentChange(v) {
      this.pageData.pindex = v;
      this.getList();
    },
    //控制每页多少条
    handleSizeChange(num) {
      this.pageData.psize = num;
      this.getList();
    },
    // 获取可用会议室
    getFreeMeetingRoom(newVal,id) {
      this.roomOptions = []
      getFreeMeetingRoom({
        startTime: newVal[0],
        endTime: newVal[1],
        meetingId: id || '',
        page: 1,
        pageSize: 9999
      }).then((res) => {   
        if (res.code == 200) {
          this.roomOptions = res.data.data.map(e => {
            return {
              label: e.roomName,
              value: e.id,
            }
          })
        } else this.$message.error(res.message);
        
        
      });
    },
    // 获取公司下人员
    getCompanyUser() {
      getCompanyUser({}).then((res) => {   
        if (res.code == 200) {
          this.options = res.data.map(e => {
            return {
              label: e.userName,
              value: e.id,
              email: e.email,
            }
          })
        } else this.$message.error(res.message);
      });
    },
    //保存
    submit() {

      this.$refs["form"].validate((valid) => {
        if (valid) {
          let URL= this.title === '修改会议' ? modify : add
          this.buttons[0].loading = true
          let obj = {
            ...this.form,
            startTime: this.form.date[0],
            endTime: this.form.date[1],
            joinUser: this.form.user.length ? this.form.user.map(item => item).join(',') : ''
          }
          URL(obj).then((res) => {
              if (res.code == 200) {
                this.$message.success(res.message)
                this.closeDialog()
                this.$refs.dialog.show()
                this.getList()
              } else this.$message.error(res.message)
              this.buttons[0].loading = false
              
            })
        }
      })
    },
    closeDialog() {
      this.form = {
        meetingSubject: "",
        date: "",
        roomId: '',
        noticeTime: "",
        joinUser: []
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.dashboard {
  padding: 20px;
}
</style>
